import { config } from './config'

type TConfigApi = {
	baseUrl: string
	headers: HeadersInit
}

export type UserBodyDto = {
	about: string
	name: string
	avatar: string
}

type ServerResponse<T> = {
	created_at?: Date
	updated_at?: Date
	__v: number
} & T

export type TUserResponseDto = ServerResponse<User>
export type TPostResponseDto = ServerResponse<Post>
export type TCommentResponseDto = ServerResponse<Comment>

class Api {
	private baseUrl
	private headers

	constructor({ baseUrl, headers }: TConfigApi) {
		this.baseUrl = baseUrl
		this.headers = headers
	}

	private onResponse(res: Response) {
		return res.ok ? res.json() : res.json().then((err) => Promise.reject(err))
	}

	private getApiUrl(path: string) {
		return `${this.baseUrl}${path}`
	}

	async getAllProducts() {
		const res = await fetch(this.getApiUrl(''), {
			method: 'GET',
			headers: this.headers,
		})
		return this.onResponse(res)
	}

	async getProducts(page: number, limit: number, search?: string) {
		const res = await fetch(
			this.getApiUrl(
				`/?page=${page}&limit=${limit}` + `${search ? `&query=${search}` : ''}`
			),
			{
				method: 'GET',
				headers: this.headers,
			}
		)
		return this.onResponse(res)
	}

	async getProduct(productId: string) {
		const res = await fetch(this.getApiUrl(`/${productId}`), {
			method: 'GET',
			headers: this.headers,
		})
		return this.onResponse(res)
	}

	async setLike(productId: string) {
		const res = await fetch(this.getApiUrl(`/likes/${productId}`), {
			method: 'PUT',
			headers: this.headers,
		})
		return this.onResponse(res)
	}

	async setDislike(productId: string) {
		const res = await fetch(this.getApiUrl(`/likes/${productId}`), {
			method: 'DELETE',
			headers: this.headers,
		})
		return this.onResponse(res)
	}
}

const api = new Api({
	baseUrl: config.apiUrl,
	headers: {
		'content-type': 'application/json',
		authorization: `Bearer ${config.apiToken}`,
	},
})

export default api
